const ROUTES = [
    {
        path: '/homepage.html',
        label: '首页',
    },
    {
        label: '文章管理',
        routes: [
            {
                path: '/article-type.html',
                label: '文章类别',
            },
            {
                path: '/article-list.html',
                label: '文章列表',
            },
            {
                path: '/article-public.html',
                label: '发表文章',
            },
        ],
    },
    {
        label: '个人中心',
        routes: [
            {
                path: '/user-info.html',
                label: '基本资料',
            },
            {
                path: '/user-avatar.html',
                label: '更换头像',
            },
            {
                path: '/user-password.html',
                label: '重置密码',
            },
        ],
    },
];

function go (path, isClick) {
    // '/article-list.html'
    if (path === 'undefined') {
        return;
    }
    $('iframe').attr({ src: path });
    // path.substr(1).split('.')[0] >>> 'article-list'
    const pathName = path.substr(1).split('.')[0];
    if (!isClick) {
        return;
    }

    location.href = `${location.origin}/#/?page=${ pathName }`;
    lastPathName = pathName;
}

window.go = go;

// 页面返显
const defaultPath = `/${ location.hash.split('=')[1] || 'homepage' }.html`; // 'article-type'
go(defaultPath);

// 渲染左侧导航
const routesHTML = ROUTES.map((item) => {
    return `
        <li class="
            layui-nav-item
            ${ defaultPath === item.path ? 'layui-this' : '' }
            ${ item.routes?.some(route => defaultPath === route.path) ? 'layui-nav-itemed' : '' }
        ">
            <a onclick="go('${ item.path }', true)">${ item.label }</a>
            ${
                item.routes
                    ? `
                        <dl class="layui-nav-child">
                            ${
                                item.routes
                                    .map(route => `
                                        <dd class="${ defaultPath === route.path ? 'layui-this' : '' }">
                                            <a onclick="go('${ route.path }', true)">${ route.label }</a>
                                        </dd>
                                    `)
                                    .join('')
                            }
                        </dl>
                    `
                    : ''
            }
        </li>
    `;
}).join('');
$('.layui-nav-tree').html(routesHTML);

// 退出登录
$('#sign-out').on('click', () => {
    localStorage.removeItem('token');
});
